package controllers;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;

import net.coobird.thumbnailator.Thumbnails;
import model.Envelope;
import model.Item;

import view.NewItemGUI;
import client.CcrmApp;

/** This Class is a New Item Controller which extends AbstractTransfer
 * 
 * @author Moran
 */

public class NewItemController extends AbstractTransfer
{

	private MarketingController prevCon;
	private NewItemGUI NewItemGUI;
	private JFileChooser fc;
	private Item item;
	private NewItemController curCont;
	
	/**
	 * this is Area Controller contractor
	 * @param TheView is New Item GUI instance
	 * @param lastCont is the prev controller instance
	 */

	public NewItemController(NewItemGUI TheView,MarketingController lastCont){
		NewItemGUI = TheView;
		prevCon = lastCont;
		curCont = this;
		NewItemGUI.addAddActionListener(new addListener());
		NewItemGUI.addBackActionListener(new backListener());
		NewItemGUI.chusefileAddActionListener(new chusefileListener());
	}
	/**
	 * Inner class that handles when chose file Button Pressed, implements ActiontListener
	 * @author Moran
	 *
	 */
	class chusefileListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			//chose the file
			 fc=new JFileChooser();
		     fc.showOpenDialog(null);
		     File f=fc.getSelectedFile();

		     //geting the path
		     if(item==null)
		    	 item=new Item();
		     item.setFilename(new String (f.getAbsolutePath()));
		     try {
		    	// File image =new File(item.getFilename());
		    	
		    	 item.setImagepath(new File(item.getFilename()));
		    	//read image
				BufferedImage bufferedimage =ImageIO.read(item.getImagepath());
				//change size to small
	
				BufferedImage thumnail=Thumbnails.of(bufferedimage).size(200, 200).asBufferedImage();
				//save in format
				ImageIcon format;
				format=new ImageIcon(thumnail);

				//jlabel1.setIcon(format);  set in GUI
				NewItemGUI.setJlabel1(format);
				//convert to byte arr
				ByteArrayOutputStream os =new ByteArrayOutputStream();
				ImageIO.write(thumnail, "jpeg", os);
				InputStream is=new ByteArrayInputStream(os.toByteArray());
				ByteArrayOutputStream bos=new ByteArrayOutputStream();
				byte[] buff=new byte[1024];
				try{
					//convert image to blob
					for(int readnum;(readnum=is.read(buff))!=-1;){
						bos.write(buff, 0, readnum);
					}
				} catch (IOException ex){
					//Logger.getLogger(arg0)
					System.out.println("image convert to blob error");	
				}
				item.setBlob(bos.toByteArray());	
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	};
	
	/**
	 * Inner class that handles when Button Add Pressed, implements ActiontListener
	 * @author Moran
	 *
	 */
	class addListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			System.out.println("creating a item to send to server");
			try{
				NewItemGUI.setWarningMesFalse();
				//creating the item model
			    if(item==null)
			    	item=new Item();
				item.setId(0);
				item.setName(new String (NewItemGUI.getItemNameText()));
				item.setDiscription(new String(NewItemGUI.getDiscription()));
				item.setPrice( Float.parseFloat((NewItemGUI.getPrice()).toString()));
				//test if all ok
				if(!(item.getName().equals("")||item.getDiscription().equals("")||item.getPrice()==0.0||item.getBlob()==null)){
					String que1 = "add new item";
					Envelope ev1 = new Envelope(item,que1);
					System.out.println("sending to server item");
					sendToServer(ev1);	
					CcrmApp.clien.setCurrObj(getCurCont());
			    }else{
			    	NewItemGUI.setWarningMes("input error");
			    }
			}
			catch(Exception e1){
				NewItemGUI.setWarningMes("input error");
			}
		}
	}
	/**
	 * handle DB Result set Warning massage
	 * @return void
	 */
	public void handleDBResult(Object ms){
		NewItemGUI.setWarningMes((String)ms);
	}
	
	/**
	 * Inner class that back Button Pressed, implements ActiontListener
	 * @author Moran
	 *
	 */
	class backListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			NewItemGUI.dispose();
			prevCon.getMarkGui().setVisible(true);
		}
	}
	/**
	 * get the current controller 
	 * @return NewItemController
	 */
	public NewItemController getCurCont() {
		return curCont;
	}
	/**
	 * get the Area View Gui
	 * @return NewItemGUI
	 */
	public NewItemGUI getAreaView() {
		return NewItemGUI;
	}
}
